package com.ff.neuropp.util;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Properties;


@Component
@Slf4j
public class MaiUtil {

	@Autowired
	private  JavaMailSender mailSender; // 自动注入的Bean

	@Value("${spring.mail.username}")
	private  String sender;

	@Value("${spring.mail.password}")
	private String password;


	/**
	 * 
	 * @param code 验证码
	 * @param mail
	 * @throws Exception
	 */
	public  void sendSimpleMail(Integer code, String mail) throws Exception {
		//String[] tos = toList.split(",");
		MimeMessage msg = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
		helper.setFrom(sender);
		helper.setTo(mail);
		helper.setSubject("NeurOpp邮箱验证码");
		helper.setText(genMailBody(helper, code), true);
		mailSender.send(msg);
	}

	private  String genMailBody(MimeMessageHelper message, Integer code) {
		StringBuilder sb = new StringBuilder("app登录验证码：<br>");
		sb.append(code);
		return sb.toString();
	}

	/**
	 *  给 谷歌邮箱发送邮件
	 * @param email
	 * @return code
	 */
	public String  gmailSender(String email) {
		Properties props = new Properties();
		gmailssl(props);

		Session session = Session.getDefaultInstance(props,
				new Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(sender, password);
					}
				});
		Message msg = new MimeMessage(session);

		try {
			msg.setFrom(new InternetAddress(sender));
			msg.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(email));
			msg.setSubject("NeurOpp邮箱验证码");
			String code = verifyCode();
			String text = new StringBuilder("app登录验证码：<br>").append(code).toString();
			msg.setText(text);
			msg.setSentDate(new Date());
			Transport.send(msg);
			return code;
		} catch (Exception e) {
			log.error("邮件发送失败 ， {}", e);
			return null;
		}

	}

	private static void gmailssl(Properties props) {
		final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
		props.put("mail.debug", "true");
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.ssl.enable", "true");
		props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
		props.put("mail.smtp.port", "465");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.auth", "true");
	}

	private static String verifyCode(){
		return String.valueOf((int)((Math.random()*9+1)*100000));
	}


}
